% Matlab file to implement class "deriv1",
% forward mode of automatic differentation, first derivatives, possibly sparse
% Michael Reiter, Universitat Pompeu Fabra, April 2007
% Last update: -
% Feel free to use, copy and modify at your own risk;
%   this program comes with NO WARRANTY WHATSOEVER
% 
% Usage:
% 1) x = deriv1(val): val is column vector
%    x is vector of independent variables, Jacobian is the identity
% 2) x = deriv1(val,iIndep): val is column vector, iIndep index of variables
%    x is vector where iIndep are independent variables, rest are constants
% 3) x = deriv1(val,0,np): val any matrix, np positive integer
%    x has zero Jacobian, assuming np independent variables
% 4) x = deriv1(val,[],J): val any matrix, J the Jacobian
%    x is matrix of values with Jacobian J
function s= deriv1s(val,iIndep,deriv)
  if(nargin==0 | nargin>3)
    error('usage: deriv1(Value,Derivative)');
  end
  s.v=val; 
  if nargin==3
    if(isscalar(iIndep) && iIndep==0)
      nIndep = deriv;
      s.d = zeros([size(val) nIndep]);
    else
      s.d=deriv;
    end
  else % only one argument
    m=size(val);
    if(length(m)~=2 | m(2)~=1)
      error('single argument to deriv1 must be column vector (independent variables)');
    end
    if(nargin==1)
      iIndep = 1:m(1);
    end
    nIndep = length(iIndep);
    s.d=zeros(m(1),nIndep);
    s.d(iIndep,:)=eye(nIndep);
    s.d = reshape(s.d,m(1),1,nIndep);
  end
  s.d = sparse(reshape(s.d,numel(s.v),nIndep));
  s=class(s,'deriv1s');
